<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-09-22 16:12:10
 * @Description: 减灾中心任务管理系统
 -->
 <template>
  <div class="task-container" :style="{ height: view.height-142 + 'px' }">
    <!-- 头部区域 -->
    <div class="header-section">
      <div class="page-title">
        <el-icon class="title-icon" size="24">
          <Document />
        </el-icon>
        <span>减灾中心任务管理</span>
      </div>
      
      <div class="header-actions">
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="handleCreateTask"
        >
          创建任务
        </el-button>
        <el-input
          v-model="searchText"
          placeholder="搜索任务名称、发起人、承接人或岗位需求..."
          style="width: 350px;"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :xs="24" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ totalCount }}</div>
              <div class="stats-label">总任务数</div>
              <el-icon class="stats-icon" size="32" color="#409eff">
                <Document />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ acceptedTaskCount }}</div>
              <div class="stats-label">已承接</div>
              <el-icon class="stats-icon" size="32" color="#67c23a">
                <CircleCheck />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ unacceptedTaskCount }}</div>
              <div class="stats-label">未承接</div>
              <el-icon class="stats-icon" size="32" color="#e6a23c">
                <Warning />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ finishedTaskCount }}</div>
              <div class="stats-label">承接中</div>
              <el-icon class="stats-icon" size="32" color="#909399">
                <Finished />
              </el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card shadow="never">
        <el-table 
          :data="filteredTasks" 
          style="width: 100%"
          row-key="id"
          v-loading="loading"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          :height="tableHeight"
        >
          <el-table-column prop="taskName" label="任务名称" width="200">
            <template #default="{ row }">
              <div class="task-name-cell">
                <div class="task-title" @click="handleViewDetail(row)" style="cursor: pointer; color: #409eff;">
                  {{ row.taskName }}
                </div>
                <div class="task-level">{{ row.taskLevel }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="initiator" label="发起人" width="120">
            <template #default="{ row }">
              <div class="initiator-cell">
                <el-avatar :size="28" class="initiator-avatar">
                  {{ row.initiator.charAt(0) }}
                </el-avatar>
                <span class="initiator-name">{{ row.initiator }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="positionRequirement" label="岗位需求" width="120">
            <template #default="{ row }">
              <el-tag 
                :type="getPositionType(row.positionRequirement)" 
                size="small"
                class="position-tag"
              >
                {{ row.positionRequirement }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="personnelCount" label="人数需求" width="100" :align="`center`">
            <template #default="{ row }">
              <el-tag type="info" size="small">
                {{ row.personnelCount }}人
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="taskStatus" label="任务状态" width="120">
            <template #default="{ row }">
              <el-tag 
                :type="getStatusType(row.taskStatus)" 
                size="small"
                class="status-tag"
              >
                {{ row.taskStatus }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="applicants" label="报名人" width="150">
            <template #default="{ row }">
              <div class="applicants-cell">
                <el-tag 
                  v-for="applicant in row.applicants.slice(0, 2)" 
                  :key="applicant"
                  size="small"
                  type="info"
                  class="applicant-tag"
                >
                  {{ applicant }}
                </el-tag>
                <el-button 
                  type="primary" 
                  size="small" 
                  text
                  @click="handleViewApplicants(row)"
                >
                  {{ row.applicants.length > 2 ? `查看全部(${row.applicants.length})` : '管理' }}
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="assignees" label="承接人" width="150">
            <template #default="{ row }">
              <div class="assignee-cell">
                <div v-if="row.assignees && row.assignees.length > 0">
                  <el-tag 
                    v-for="assignee in row.assignees.slice(0, 2)" 
                    :key="assignee"
                    size="small"
                    type="success"
                    class="assignee-tag"
                  >
                    {{ assignee }}
                  </el-tag>
                  <span v-if="row.assignees.length > 2" class="more-assignees">
                    +{{ row.assignees.length - 2 }}
                  </span>
                </div>
                <span v-else class="no-assignee">未分配</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="workHours" label="任务工时" width="180">
            <template #default="{ row }">
              <div class="work-hours-cell">
                <div class="start-time">开始：{{ row.workHours.startDate }}</div>
                <div class="end-time">结束：{{ row.workHours.endDate }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="deadline" label="截止日期" width="120">
            <template #default="{ row }">
              <div class="deadline-cell">
                <el-icon><Calendar /></el-icon>
                <span :class="{ 'deadline-urgent': isDeadlineUrgent(row.deadline) }">
                  {{ row.deadline }}
                </span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="taskContent" label="任务内容" min-width="200">
            <template #default="{ row }">
              <div class="task-content">
                <!-- <el-tooltip :content="row.taskContent" placement="top-start"> -->
                  <div class="content-text" :title="row.taskContent">
                    {{ truncateText(row.taskContent, 60) }}
                  </div>
                <!-- </el-tooltip> -->
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="attachments" label="附件" width="100">
            <template #default="{ row }">
              <div class="attachments-cell">
                <el-icon 
                  v-if="row.attachments && row.attachments.length > 0" 
                  class="attachment-icon"
                  size="18"
                  color="#409eff"
                >
                  <Paperclip />
                </el-icon>
                <span v-if="row.attachments && row.attachments.length > 0" class="attachment-count">
                  {{ row.attachments.length }}
                </span>
                <span v-else class="no-attachment">无</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  text
                  @click="handleViewDetail(row)"
                >
                  详情
                </el-button>
                <el-button 
                  type="success" 
                  size="small" 
                  text
                  @click="handleEditTask(row)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  text
                  @click="handleDeleteTask(row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 任务详情对话框 -->
    <TaskDetail
      v-model:visible="detailVisible"
      :task="selectedTask"
      @refresh="loadTaskData"
    />

    <!-- 报名人管理对话框 -->
    <ApplicantsDialog
      v-model:visible="applicantsVisible"
      :task="selectedTask"
      @refresh="loadTaskData"
    />

    <!-- 任务表单对话框 -->
    <TaskForm
      v-model:visible="taskFormVisible"
      :task="selectedTask"
      :is-edit="isEditMode"
      @refresh="loadTaskData"
    />
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Document,
  Search,
  CircleCheck,
  Warning,
  Finished,
  Calendar,
  Paperclip,
  Plus
} from '@element-plus/icons-vue';
import TaskDetail from './TaskDetail.vue';
import ApplicantsDialog from './ApplicantsDialog.vue';
import TaskForm from './TaskForm.vue';

// 任务信息接口定义
interface TaskInfo {
  id: number;
  initiator: string;
  taskLevel: string;
  taskName: string;
  positionRequirement: string;
  taskContent: string;
  personnelCount: number;
  applicants: string[];
  assignees: string[]; // 修改为数组，支持多人承接
  workHours: {
    startDate: string;
    endDate: string;
  };
  deadline: string;
  taskStatus: string;
  attachments: string[] | null;
  createdAt?: string;
  updatedAt?: string;
}

onMounted(() => {
  loadTaskData();
});

var view = reactive({
  height: window.innerHeight,
});

// 响应式数据
const searchText = ref<string>('');
const loading = ref<boolean>(false);
const taskList = ref<TaskInfo[]>([]);

// 对话框控制
const detailVisible = ref(false);
const applicantsVisible = ref(false);
const taskFormVisible = ref(false);
const isEditMode = ref(false);
const selectedTask = ref<TaskInfo | null>(null);

// 计算属性
const filteredTasks = computed(() => {
  if (!searchText.value) return taskList.value;
  
  return taskList.value.filter(task => 
    task.taskName.toLowerCase().includes(searchText.value.toLowerCase()) ||
    task.initiator.toLowerCase().includes(searchText.value.toLowerCase()) ||
    task.positionRequirement.toLowerCase().includes(searchText.value.toLowerCase()) ||
    (task.assignees && task.assignees.some(assignee => 
      assignee.toLowerCase().includes(searchText.value.toLowerCase())
    )) ||
    task.applicants.some(applicant => 
      applicant.toLowerCase().includes(searchText.value.toLowerCase())
    )
  );
});

const totalCount = computed(() => taskList.value.length);

const acceptedTaskCount = computed(() => 
  taskList.value.filter(t => t.taskStatus === '已承接').length
);

const unacceptedTaskCount = computed(() => 
  taskList.value.filter(t => t.taskStatus === '未承接').length
);

const finishedTaskCount = computed(() => 
  taskList.value.filter(t => t.taskStatus === '任务结束').length
);

const tableHeight = computed(() => {
  return view.height - 360;
});

// 方法
const loadTaskData = () => {
  loading.value = true;
  
  // 模拟任务数据，修改assignee为assignees数组
  setTimeout(() => {
    taskList.value = [
      {
        id: 1,
        initiator: "张主任",
        taskLevel: "部门任务",
        taskName: "水库安全监测数据分析",
        positionRequirement: "科研助理",
        taskContent: "负责分析山东省小型水库监测数据，包括水位、流量等关键指标的统计分析，并编制相关技术报告",
        personnelCount: 2,
        applicants: ["李明", "王小红", "赵强"],
        assignees: ["李明", "王小红"],
        workHours: {
          startDate: "2025-09-20",
          endDate: "2025-10-15"
        },
        deadline: "2025-10-15",
        taskStatus: "已承接",
        attachments: ["监测数据.xlsx", "技术要求.pdf"],
        createdAt: "2025-09-18",
        updatedAt: "2025-09-19"
      },
      {
        id: 2,
        initiator: "陈工程师",
        taskLevel: "项目任务",
        taskName: "防洪调度系统优化",
        positionRequirement: "技术开发",
        taskContent: "优化现有防洪调度系统的算法模块，提升计算效率和预警准确性，包括前端界面改进和后端逻辑优化",
        personnelCount: 1,
        applicants: ["张技术", "刘开发"],
        assignees: [],
        workHours: {
          startDate: "2025-10-01",
          endDate: "2025-11-30"
        },
        deadline: "2025-11-30",
        taskStatus: "未承接",
        attachments: ["系统架构图.png", "需求文档.docx", "测试数据.sql"],
        createdAt: "2025-09-17",
        updatedAt: "2025-09-18"
      },
      {
        id: 3,
        initiator: "李部长",
        taskLevel: "部门任务",
        taskName: "年度工作总结材料整理",
        positionRequirement: "业务秘书",
        taskContent: "整理2025年度减灾中心各部门工作总结材料，编制综合报告，协调各部门数据收集和格式统一",
        personnelCount: 1,
        applicants: ["王秘书"],
        assignees: ["王秘书"],
        workHours: {
          startDate: "2025-09-15",
          endDate: "2025-09-30"
        },
        deadline: "2025-09-30",
        taskStatus: "任务结束",
        attachments: ["模板.docx"],
        createdAt: "2025-09-10",
        updatedAt: "2025-09-30"
      },
      {
        id: 4,
        initiator: "赵研究员",
        taskLevel: "项目任务",
        taskName: "气象预警模型验证",
        positionRequirement: "科研助理",
        taskContent: "对新开发的气象预警模型进行历史数据验证，分析模型准确率，优化参数配置，编写验证报告",
        personnelCount: 1,
        applicants: ["孙研究", "钱助理"],
        assignees: ["孙研究"],
        workHours: {
          startDate: "2025-09-25",
          endDate: "2025-10-20"
        },
        deadline: "2025-10-20",
        taskStatus: "已承接",
        attachments: ["历史数据.csv", "模型文档.pdf"],
        createdAt: "2025-09-20",
        updatedAt: "2025-09-20"
      },
      {
        id: 5,
        initiator: "周主管",
        taskLevel: "部门任务",
        taskName: "设备采购清单制作",
        positionRequirement: "业务秘书",
        taskContent: "制作2026年度设备采购清单，包括预算编制、供应商调研、技术参数确认等工作",
        personnelCount: 1,
        applicants: [],
        assignees: [],
        workHours: {
          startDate: "2025-10-10",
          endDate: "2025-10-25"
        },
        deadline: "2025-10-25",
        taskStatus: "未承接",
        attachments: null,
        createdAt: "2025-09-22",
        updatedAt: "2025-09-22"
      },
      {
        id: 6,
        initiator: "吴教授",
        taskLevel: "项目任务",
        taskName: "洪水风险评估报告",
        positionRequirement: "科研助理",
        taskContent: "基于最新的洪水模型和历史数据，编制华北地区洪水风险评估报告，包括风险等级划分和防御建议",
        personnelCount: 2,
        applicants: ["马研究", "朱助理", "徐工程师"],
        assignees: [],
        workHours: {
          startDate: "2025-10-05",
          endDate: "2025-12-15"
        },
        deadline: "2025-12-15",
        taskStatus: "未承接",
        attachments: ["数据清单.xlsx", "技术规范.pdf"],
        createdAt: "2025-09-21",
        updatedAt: "2025-09-21"
      },
      {
        id: 7,
        initiator: "胡经理",
        taskLevel: "部门任务",
        taskName: "会议筹备和组织",
        positionRequirement: "业务秘书",
        taskContent: "筹备2025年减灾技术交流会，包括场地预订、专家邀请、材料准备、会务安排等全流程服务",
        personnelCount: 1,
        applicants: ["高秘书", "任助理"],
        assignees: ["高秘书"],
        workHours: {
          startDate: "2025-09-18",
          endDate: "2025-11-10"
        },
        deadline: "2025-11-10",
        taskStatus: "已承接",
        attachments: ["会议议程.docx", "专家名单.xlsx"],
        createdAt: "2025-09-15",
        updatedAt: "2025-09-18"
      },
      {
        id: 8,
        initiator: "郭工程师",
        taskLevel: "项目任务",
        taskName: "监测平台数据迁移",
        positionRequirement: "技术开发",
        taskContent: "将旧版监测平台的历史数据迁移到新系统，确保数据完整性和准确性，编写迁移脚本和测试方案",
        personnelCount: 1,
        applicants: ["程开发"],
        assignees: ["程开发"],
        workHours: {
          startDate: "2025-09-10",
          endDate: "2025-09-25"
        },
        deadline: "2025-09-25",
        taskStatus: "任务结束",
        attachments: ["数据库结构.sql", "迁移方案.docx"],
        createdAt: "2025-09-05",
        updatedAt: "2025-09-25"
      }
    ];

    loading.value = false;
  }, 1000);
};

// 任务操作方法
const handleCreateTask = () => {
  selectedTask.value = null;
  isEditMode.value = false;
  taskFormVisible.value = true;
};

const handleEditTask = (task: TaskInfo) => {
  selectedTask.value = { ...task };
  isEditMode.value = true;
  taskFormVisible.value = true;
};

const handleDeleteTask = async (task: TaskInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务"${task.taskName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    // 模拟删除操作
    const index = taskList.value.findIndex(t => t.id === task.id);
    if (index > -1) {
      taskList.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handleViewDetail = (task: TaskInfo) => {
  selectedTask.value = task;
  detailVisible.value = true;
};

const handleViewApplicants = (task: TaskInfo) => {
  selectedTask.value = task;
  applicantsVisible.value = true;
};

// 工具方法
const getPositionType = (position: string) => {
  const positionMap: Record<string, string> = {
    '科研助理': 'success',
    '业务秘书': 'primary',
    '技术开发': 'warning'
  };
  return positionMap[position] || 'info';
};

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '已承接': 'success',
    '未承接': 'warning',
    '任务结束': 'info'
  };
  return statusMap[status] || 'info';
};

const isDeadlineUrgent = (deadline: string) => {
  const today = new Date();
  const deadlineDate = new Date(deadline);
  const diffTime = deadlineDate.getTime() - today.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays <= 7 && diffDays >= 0;
};

const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
};
</script>

<style lang="scss" scoped>
.task-container {
  padding: 0 20px;
  background-color: #f5f7fa;
  overflow: auto;
}

.header-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;

  .page-title {
    display: flex;
    align-items: center;
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    
    .title-icon {
      margin-right: 8px;
      color: #409eff;
    }
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }
}

.stats-section {
  margin-bottom: 16px;

  .stats-card {
    .stats-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .stats-value {
        font-size: 28px;
        font-weight: bold;
        color: #409eff;
      }
      
      .stats-label {
        color: #909399;
        margin-top: 4px;
        font-size: 14px;
      }
      
      .stats-icon {
        opacity: 0.8;
      }
    }
  }
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.task-name-cell {
  .task-title {
    font-weight: 500;
    margin-bottom: 4px;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  .task-level {
    font-size: 12px;
    color: #909399;
  }
}

.initiator-cell, .assignee-cell {
  display: flex;
  align-items: center;
  
  .initiator-avatar, .assignee-avatar {
    margin-right: 8px;
    background: linear-gradient(45deg, #409eff, #67c23a);
  }
  
  .initiator-name, .assignee-name {
    font-size: 13px;
  }
}

.no-assignee {
  color: #909399;
  font-size: 12px;
}

.assignee-cell {
  .assignee-tag {
    margin-right: 4px;
    margin-bottom: 2px;
  }
  
  .more-assignees {
    color: #909399;
    font-size: 12px;
  }
}

.applicants-cell {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
  
  .applicant-tag {
    margin-right: 4px;
    margin-bottom: 2px;
  }
}

.work-hours-cell {
  .start-time, .end-time {
    font-size: 12px;
    margin-bottom: 2px;
  }
  
  .start-time {
    color: #67c23a;
  }
  
  .end-time {
    color: #e6a23c;
  }
}

.deadline-cell {
  display: flex;
  align-items: center;
  font-size: 13px;
  
  :deep(.el-icon) {
    margin-right: 6px;
    color: #909399;
  }
  
  .deadline-urgent {
    color: #f56c6c;
    font-weight: 500;
  }
}

.task-content {
  .content-text {
    line-height: 1.4;
    color: #ccc;
    cursor: pointer;
    
    &:hover {
      color: #409eff;
    }
  }
}

.attachments-cell {
  display: flex;
  align-items: center;
  
  .attachment-icon {
    margin-right: 4px;
  }
  
  .attachment-count {
    color: #409eff;
    font-size: 12px;
  }
  
  .no-attachment {
    color: #c0c4cc;
    font-size: 12px;
  }
}

.position-tag, .status-tag {
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

// 响应式样式
@media (max-width: 768px) {
  .task-container {
    padding: 10px;
  }
  
  .header-section {
    flex-direction: column;
    align-items: stretch;
    
    .header-actions {
      justify-content: center;
    }
  }
}
</style>

<style lang="scss">
// 全局样式覆盖
.task-container {
  .el-card__body {
    padding: 16px;
  }
  
  .el-table {
    .el-table__body-wrapper {
      scrollbar-width: thin;
      scrollbar-color: #ddd transparent;
      
      &::-webkit-scrollbar {
        height: 6px;
        width: 6px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 3px;
      }
    }
  }
}
</style>